from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Caeousel,Good,GoodImg
from .serlislizer import CarouselAPIViewSer
from.models import GoodCategory
from .serlislizer import GoodSer,GoodImgSer
from functools import reduce
# Create your views here.

# 轮播图
class CarouselAPIView(APIView):
    def get(self,request):
        # 查询所有轮播图
        Carousel_queryset =Caeousel.objects.all()
        Carousel_queryset_ser = CarouselAPIViewSer(Carousel_queryset,many=True)
        return Response({"code":200,"msg":"获取轮播图成功","carousel":Carousel_queryset_ser.data})


class OneCategoryGoods(APIView):
    def get(self,request):
        # 1获取前端类别
        cate_name = request.query_params.get("categoryName")
        try:
            cate_obj = GoodCategory.objects.get(cate_name=cate_name)
        except:
            return Response({"code":204,"msg":"该类别不存在"})
       # 2 根据类别名，查询类别对象
        goods_queryset = cate_obj.good_set.all()
        # 3类别对象，反向查询该类别所有商品
        goods_queryset_set =GoodSer(goods_queryset,many=True)
        return Response(goods_queryset_set.data)


# 热门商品
class HotProduct(APIView):
    def get(self,request):
        # 获取商品类别
        print ("查看类别:",request.query_params)
        cate_list =request.query_params.getlist("categoryName[]")
        print ("类别",cate_list)
        # 根据类别名，查询商品类别对象列表
        cate_obj_list = [GoodCategory.objects.get(cate_name=i)for i in cate_list]
        # 根据每一个类别对象，反向查询对应的所有商品
        good_queryset_list =[i.good_set.all()for i in cate_obj_list]
        # 将所有商品集合 进行 合并 操作
        # temp =set()
        # for i in good_queryset_list:
        #     temp |= i
        goods_queryset = reduce (lambda x,y:x|y,good_queryset_list)
        # 将所有商品进行序列化
        goods_queryset_ser =GoodSer(goods_queryset, many =True)
        return Response(goods_queryset_ser.data)

        return Response({"code":200,"msg":"加载热门商品"})













